import {
  Component, OnInit, AfterViewInit, OnDestroy, Input, AfterViewChecked, Output,
  EventEmitter
} from '@angular/core';
import {flyIn} from "../animations/flyIn";
import 'tinymce';
import 'tinymce/themes/modern';

import 'tinymce/plugins/table';
import 'tinymce/plugins/link';
import 'tinymce/plugins/advlist';
import 'tinymce/plugins/autolink';
import 'tinymce/plugins/lists';
import 'tinymce/plugins/link';
import 'tinymce/plugins/image';
import 'tinymce/plugins/charmap';
import 'tinymce/plugins/print';
import 'tinymce/plugins/hr';
import 'tinymce/plugins/anchor';
import 'tinymce/plugins/pagebreak';
import 'tinymce/plugins/searchreplace';
import 'tinymce/plugins/wordcount';
import 'tinymce/plugins/visualblocks';
import 'tinymce/plugins/visualchars';
import 'tinymce/plugins/code';
import 'tinymce/plugins/fullscreen';
import 'tinymce/plugins/insertdatetime';
import 'tinymce/plugins/media';
import 'tinymce/plugins/nonbreaking';
import 'tinymce/plugins/save';
import 'tinymce/plugins/table';
import 'tinymce/plugins/contextmenu';
import 'tinymce/plugins/directionality';
import 'tinymce/plugins/emoticons';
import 'tinymce/plugins/template';
import 'tinymce/plugins/paste';
import 'tinymce/plugins/textcolor';
import 'tinymce/plugins/colorpicker';
import 'tinymce/plugins/textpattern';
import 'tinymce/plugins/imagetools';
import 'tinymce/plugins/codesample';
import 'tinymce/plugins/preview';
import {HttpService} from "../share/http.service";


declare var tinymce: any;
@Component({
  selector: 'app-write-post',
  templateUrl: './write-post.component.html',
  styleUrls: ['./write-post.component.scss'],
  animations: [
    flyIn
  ]
})


export class WritePostComponent implements OnInit, AfterViewInit, OnDestroy, AfterViewChecked {
  public editor;
  public content: string = "";
  public title: string = "";
  public editorleft;
  public tinymceContent = {right: '', left: ''};
  public richText :any ={};
  public tinymceRightContent: string;
  @Input()
  comeFromModalText: string;

  @Output()
  RichTextGoOut:EventEmitter<any>=new EventEmitter();

  constructor(private http: HttpService) {
  }


  public fileInputChangeHandler(): void {
    // console.log(123)
    // let fileInput = <HTMLInputElement>document.getElementById('img_input');
    // console.log(fileInput);
    // let inputValue=fileInput.value;
    // console.log(inputValue+1);
    // if(!inputValue){
    //   return;
    // }
    //
    // //提交隐藏的表单，上传文件
    // let fileForm=<HTMLFormElement>document.getElementById('file_upload_form');
    // console.log(fileForm);
    // let file=fileInput.files[0];
    // console.log(file);
    // let formData = new FormData();
    // formData.append('file', file,file.name);
    // console.log(formData);

    let files = $("#img_input").prop('files');
    console.log(files);
    let formData = new FormData();
    formData.append("file", files[0]);
    console.log(files[0]);
    $.ajax({
      url: 'http://192.168.0.46/manage/upload',
      type: 'POST',
      data: formData,
      contentType: false,
      processData: false,
      // async: false,
      // cache: false,
      // contentType: false,
      // processData: false,
      success: function (returndata) {
        console.log(returndata);
      },
      error: function (returndata) {
        console.log(returndata);
      }
    });
    // fileForm.action="fileuploadurl";
    // fileForm.onsubmit=function(event){
    //     console.log(event);
    //     event.preventDefault();
    //     let file=fileInput.files[0];
    //     console.log(file);
    //     let formData = new FormData();
    //     formData.append('file', file,file.name);
    //
    //     let xhr=new XMLHttpRequest();
    //     xhr.withCredentials = false;
    //     xhr.open('POST', 'http://192.168.0.46/manage/upload');
    //     xhr.onload = function() {
    //         let json;
    //         if (xhr.status != 200) {
    //           console.log('HTTP Error: ' + xhr.status);
    //           return;
    //         }
    //         json = JSON.parse(xhr.responseText);
    //         if (!json || typeof json.location != 'string') {
    //           console.log('Invalid JSON: ' + xhr.responseText);
    //           return;
    //         }
    //         console.log(json.location);
    //         fileInput.value='';
    //     };
    //     xhr.send(formData);
    // }
    // fileForm.submit();
    // fileInput.value='';
  }

  onSubmit() {
    // console.log(1234);
    // console.log(this.content);
    //   $.ajax({
    //     method:'post',
    //     url:"http://localhost:8083/app1/app2/web/manage/product/image/upload",
    //     data:{
    //       picture:'images/img.jpg'
    //     },
    //     async: false,
    //     cache: false,
    //     contentType: 'application/file',
    //     processData: false,
    //     success(data){
    //
    //       console.log("请求成功"+data)
    //     },
    //     error(err){
    //       console.log(err)
    //     }
    //   });
    // this.http.httpDelete("http://192.168.0.46/web/manage/pagehtml/delete", {
    //   id: 1
    // }).subscribe(res => console.log(res))
  }
  //upload()
  // //
  unload() {
    //
    // let fileInput = <HTMLInputElement>document.getElementById('file1');
    // formData.append("myfile", fileInput.files[0],fileInput.files[0].name);
    // console.log(234)
    // console.log(fileInput.files[0].name);
    var files = $("#file1").prop('files');
    console.log(files + 2);
    var formData = new FormData();
    formData.append("file", files[0])
    $.ajax({
      url: "http://localhost:8083/app1/app2/web/manage/product/image/upload",
      type: "POST",
      data: formData,
      /**
       *必须false才会自动加上正确的Content-Type
       */
      contentType: false,
      /**
       * 必须false才会避开jQuery对 formdata 的默认处理
       * XMLHttpRequest会对 formdata 进行正确的处理
       */
      processData: false,
      success: function (data) {
        // var jsonObj = $.parseJSON(data)
        console.log(data)
        // $("#imgWait")
      },
      error: function () {
        alert("上传失败！");
        $("#imgWait").hide();
      }
    });
  }

  ngAfterViewInit() {
    /**
     *  【非常重要】
     *  关于TinyMCE的完整文档，请查看这里https://www.tinymce.com/docs/
     */
    setTimeout(()=>{
      tinymce.init({
        selector: '#post_editor',
        skin_url: '/assets/skins/lightgray',
        //menubar:false,
        // 'advlist autolink lists link image charmap print preview hr anchor pagebreak',
        // 'searchreplace wordcount visualblocks visualchars code fullscreen',
        // 'insertdatetime media nonbreaking save table contextmenu directionality',
        // 'emoticons template paste textcolor colorpicker textpattern imagetools codesample'
        plugins: [
          'advlist autolink lists link charmap preview hr anchor pagebreak',
          'searchreplace wordcount visualblocks visualchars code fullscreen',
          'insertdatetime nonbreaking save table contextmenu directionality',
          'emoticons template paste textcolor colorpicker textpattern codesample'
        ],
        toolbar1: 'insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image',
        toolbar2: 'print preview media | forecolor backcolor emoticons | codesample',
        image_advtab: true,
        codesample_content_css: '/assets/css/prism.css',
        //文件和图片上传相关的选项
        file_browser_callback_types: 'image',
        file_browser_callback: function (field_name, url, type, win) {
          console.log(type);
          console.log(type == 'image');
          if (type == 'image') {
            let event = new MouseEvent('click', {
              'view': window,
              'bubbles': true,
              'cancelable': true
            });
            let fileInput = document.getElementById('img_input');
            fileInput.dispatchEvent(event);
          }
        },
        setup: editor => {
          // editor.setContent("12345");
          this.editor = editor;
          editor.on('blur', () => {
            this.tinymceContent.left = editor.getContent();
            this.RichTextGoOut.emit(this.tinymceContent);
            // console.log(this.tinymceContent)
            // this.content = editor.getContent();
          });
        }
      });

      tinymce.init({
        selector: '#post_editor_left',
        skin_url: '/assets/skins/lightgray',
        //menubar:false,
        plugins: [
          'advlist autolink lists link charmap preview hr anchor pagebreak',
          'searchreplace wordcount visualblocks visualchars',
          'insertdatetime nonbreaking save table contextmenu directionality',
          'template paste textcolor colorpicker textpattern codesample'
        ],
        toolbar1: 'insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image',
        toolbar2: 'print preview media | forecolor backcolor emoticons | codesample',
        image_advtab: true,
        codesample_content_css: '/assets/css/prism.css',
        //文件和图片上传相关的选项
        // file_browser_callback_types: 'image',
        // file_browser_callback: function (field_name, url, type, win) {
        //   if (type == 'image') {
        //     let event = new MouseEvent('click', {
        //       'view': window,
        //       'bubbles': true,
        //       'cancelable': true
        //     });
        //     let fileInput = document.getElementById('img_input');
        //     fileInput.dispatchEvent(event);
        //   }
        // },
        setup: editor => {
          this.editorleft = editor;
          editor.on('blur', () => {
            this.tinymceContent.right = editor.getContent();
            this.RichTextGoOut.emit(this.tinymceContent);
            // console.log(this.tinymceContent);
            // this.content = editor.getContent();
          });
        }
      });
    },1000);
    // this.editor.setContent(this.comeFromModalText);
    // this.editorleft.setContent(this.comeFromModalText);
    setTimeout(()=>{
      let reg =/\[\{.*?\}\]/;
      let boolean = reg.test(this.comeFromModalText);
      if(this.comeFromModalText && boolean){
        console.log(this.comeFromModalText);
        let value = JSON.parse(this.comeFromModalText);
        // console.log(value);
        this.richText.right = value[0].html;
        this.richText.left = value[1].html;
      }else{
        // console.log(this.comeFromModalText)
        this.richText.right=this.comeFromModalText;
        this.richText.left = '';
      }
      // console.log(this.richText);
      // console.log(this.editor);
      if(this.richText){
        this.editor.setContent(this.richText.left);
        this.editorleft.setContent(this.richText.right);
      }
    },1075)
  }

  ngOnInit() {

  }

  ngAfterViewChecked() {

  }

  ngOnDestroy() {
    tinymce.remove(this.editor);
    tinymce.remove(this.editorleft)
  }
}
